package com.sky.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    private IgnoreUrlsConfig ignoreUrlsConfig;

    @Autowired
    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;

    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Bean
    SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        HttpSecurity http = httpSecurity.authorizeHttpRequests(authz -> {
            //不需要保护的资源路径允许访问
            for (String url : ignoreUrlsConfig.getUrls()) {
                authz.requestMatchers(url).permitAll();
            }

            //允许跨域请求的OPTIONS请求
            authz.requestMatchers(HttpMethod.OPTIONS).permitAll();

            // 所有其他请求必须认证
            authz.anyRequest().authenticated();
        });

        // 2. 关闭 CSRF（前后端分离无需 CSRF）
        http.csrf(csrf -> csrf.disable());

        // 3. 无状态：不使用 Session
        http.sessionManagement(session ->
                session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        );

//        http.cors(cors -> cors.configurationSource(request -> {
//            CorsConfiguration config = new CorsConfiguration();
//            config.setAllowedOriginPatterns(Arrays.asList("*")); // Spring Boot 2.4+ 推荐用 patterns
//            config.setAllowedMethods(Arrays.asList("*"));
//            config.setAllowedHeaders(Arrays.asList("*"));
//            config.setAllowCredentials(true); // 如果前端需要带 cookie
//            return config;
//        }));

        // 4. 自定义认证/授权异常处理器
        http.exceptionHandling(exception ->
                exception
                        .accessDeniedHandler(restfulAccessDeniedHandler)      // 403
                        .authenticationEntryPoint(restAuthenticationEntryPoint) // 401
        );

        // 5. 添加 JWT 认证过滤器（在用户名密码过滤器之前）
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();

    }
}
